import numpy as np
import cv2
import sys
import os


def resize_bilinear_interpolation(src,dst,dst_h,dst_w):
    '''
    scale_y = src_h/dis_h = src_y/dis_y

    '''
    # dst =  np.zeros_like(src)
    src_h,src_w = src.shape[:2]
    scale_y =src_h/dst_h
    scale_x =src_w/dst_w
    for n in range(3): # 对channel循环
        for dst_y in range(dst_h): # 对height循环
            for dst_x in range(dst_w): # 对width循环
                # 目标在源上的坐标
                src_x = (dst_x + 0.5) * scale_x - 0.5
                src_y = (dst_y + 0.5) * scale_y - 0.5
                # 计算在源图上四个近邻点的位置
                src_x_0 = int(np.floor(src_x))
                src_y_0 = int(np.floor(src_y))
                src_x_1 = min(src_x_0 + 1, src_w - 1)
                src_y_1 = min(src_y_0 + 1, src_h - 1)
 
                # 双线性插值
                value0 = (src_x_1 - src_x) * src[src_y_0, src_x_0, n] + (src_x - src_x_0) * src[src_y_0, src_x_1, n]
                value1 = (src_x_1 - src_x) * src[src_y_1, src_x_0, n] + (src_x - src_x_0) * src[src_y_1, src_x_1, n]
                dst[dst_y, dst_x, n] = int((src_y_1 - src_y) * value0 + (src_y - src_y_0) * value1)

                #近邻
                # dst[dst_y, dst_x, n] = src[src_y_0,src_x_0,n]
    return dst

if __name__=="__main__":
    src = cv2.imread("../data/cat.png")
    print(src.shape)
    src_h,src_w=src.shape[:2]
    # dis_h,dis_w = int(src_h/3),int(src_w/3)
    dis_h,dis_w = 800,400
    dst =  np.zeros([dis_h,dis_w,3])
    print(dst.shape)

    dis = resize_bilinear_interpolation(src,dst,dis_h,dis_w)
    cv2.imwrite("../results/cat_python_near.jpg",dis)
    cv2.imshow("name",dis)
    cv2.waitKey()